package com.labbit.platform.commons.session;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.labbit.platform.commons.properties.CommonProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * guava session 存储
 * @author ChenYu
 * @date 2017/12/14 16:19
 */
@Component("guavaSession")
public class GuavaSession<E> implements ISession<E> {

    @Autowired
    private CommonProperties commonProperties;

    private Cache<String, E> cache;


    @Override
    public E get(String key) {
        if (null == cache) return null;
        return cache.getIfPresent(key);
    }

    @Override
    public void put(String key, E session) {
        if (null == cache) {
            synchronized (GuavaSession.class) {
                if (null == cache) {
                    cache = CacheBuilder.newBuilder()
                    .maximumSize(1000)
                    .expireAfterAccess(commonProperties.getSessionTimeout(), TimeUnit.SECONDS)
                    .build();
                }
            }
        }
        cache.put(key, session);
    }

    @Override
    public void remove(String key) {
        cache.invalidate(key);
    }

    @Override
    public void removeAll() {
        cache.invalidateAll();
    }

}
